// API 配置和请求工具 vite api配置  import.meta.env.VITE_API_BASE_URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL
console.log(API_BASE_URL,'API_BASE_URL')
// 获取token的函数
const getToken = () => {
  return localStorage.getItem('token')
}

// 请求配置
const defaultHeaders = {
  'Content-Type': 'application/json'
}

// 通用请求函数
async function request(url, options = {}) {
  const token = getToken()
  const config = {
    headers: { 
      ...defaultHeaders, 
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...options.headers 
    },
    ...options
  }

  try {
    const response = await fetch(`${API_BASE_URL}${url}`, config)
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      
      // 如果是401错误，清除token并跳转到登录页
      if (response.status === 401) {
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        if (window.location.pathname !== '/login') {
          window.location.href = '/login'
        }
      }
      
      throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`)
    }

    return await response.json()
  } catch (error) {
    console.error('API请求失败:', error)
    throw error
  }
}

// API 方法
export const api = {
  // 上传相关
  uploads: {
    uploadImage: async (file) => {
      const token = localStorage.getItem('token')
      const formData = new FormData()
      formData.append('file', file)
      const response = await fetch(`${API_BASE_URL}/uploads/images`, {
        method: 'POST',
        headers: {
          ...(token ? { Authorization: `Bearer ${token}` } : {})
        },
        body: formData
      })
      if (!response.ok) {
        const err = await response.json().catch(() => ({}))
        throw new Error(err.message || `HTTP ${response.status}: ${response.statusText}`)
      }
      return await response.json()
    }
  },
  // 认证相关
  auth: {
    // 登录
    login: (credentials) => request('/auth/login', {
      method: 'POST',
      body: JSON.stringify(credentials)
    }),
    
    // 注册
    register: (userData) => request('/auth/register', {
      method: 'POST',
      body: JSON.stringify(userData)
    }),
    
    // 获取当前用户信息
    me: () => request('/auth/me'),
    
    // 修改密码
    changePassword: (data) => request('/auth/change-password', {
      method: 'PUT',
      body: JSON.stringify(data)
    }),
    
    // 忘记密码
    forgotPassword: (data) => request('/auth/forgot-password', {
      method: 'POST',
      body: JSON.stringify(data)
    }),
    
    // 重置密码
    resetPassword: (data) => request('/auth/reset-password', {
      method: 'POST',
      body: JSON.stringify(data)
    }),
    
    // 刷新token
    refreshToken: () => request('/auth/refresh', {
      method: 'POST'
    })
  },

  // 项目相关
  projects: {
    // 获取项目列表
    list: (params = {}) => {
      const searchParams = new URLSearchParams(params)
      return request(`/projects?${searchParams}`)
    },
    
    // 获取项目详情
    getById: (id) => request(`/projects/${id}`),
    
    // 获取项目完整配置
    getConfig: (id) => request(`/projects/${id}/config`),
    
    // 创建项目
    create: (data) => request('/projects', {
      method: 'POST',
      body: JSON.stringify(data)
    }),
    
    // 更新项目
    update: (id, data) => request(`/projects/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data)
    }),
    
    // 删除项目
    delete: (id) => request(`/projects/${id}`, {
      method: 'DELETE'
    }),
    
    // 获取项目统计
    stats: () => request('/projects/stats'),

    // 前置页：获取
    getFrontMatter: (id) => request(`/projects/${id}/front-matter`),
    // 前置页：更新
    updateFrontMatter: (id, data) => request(`/projects/${id}/front-matter`, {
      method: 'PUT',
      body: JSON.stringify(data)
    })
  },

  // 章节相关
  sections: {
    // 获取项目章节列表
    list: (projectId, params = {}) => {
      const searchParams = new URLSearchParams(params)
      return request(`/projects/${projectId}/sections?${searchParams}`)
    },
    
    // 获取所有模板章节
    listAll: () => request('/sections/templates'),
    
    // 获取章节详情
    getById: (id) => request(`/sections/${id}`),
    
    // 创建章节
    create: (projectId, data) => request(`/projects/${projectId}/sections`, {
      method: 'POST',
      body: JSON.stringify(data)
    }),
    
    // 更新章节
    update: (id, data) => request(`/sections/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data)
    }),
    
    // 删除章节
    delete: (id) => request(`/sections/${id}`, {
      method: 'DELETE'
    }),
    
    // 重新排序章节
    reorder: (projectId, sections) => request(`/projects/${projectId}/sections/reorder`, {
      method: 'PUT',
      body: JSON.stringify({ sections })
    })
  },

  // 表单相关
  forms: {
    // 获取所有表单列表
    listAll: (params = {}) => {
      const searchParams = new URLSearchParams(params)
      return request(`/forms?${searchParams}`)
    },
    
    // 获取章节下的表单列表
    list: (sectionId) => request(`/sections/${sectionId}/forms`),
    
    // 获取表单详情
    getById: (id) => request(`/forms/${id}`),
    
    // 创建独立表单（不关联章节）
    create: (data) => request('/forms', {
      method: 'POST',
      body: JSON.stringify(data)
    }),
    
    // 在章节下创建表单
    createInSection: (sectionId, data) => request(`/sections/${sectionId}/forms`, {
      method: 'POST',
      body: JSON.stringify(data)
    }),
    
    // 更新表单基本信息
    update: (id, data) => request(`/forms/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data)
    }),
    
    // 更新表单配置
    updateConfig: (id, data) => request(`/forms/${id}/config`, {
      method: 'PUT',
      body: JSON.stringify(data)
    }),
    
    // 删除表单
    delete: (id) => request(`/forms/${id}`, {
      method: 'DELETE'
    }),
    
    // 复制表单
    copy: (id, data) => request(`/forms/${id}/copy`, {
      method: 'POST',
      body: JSON.stringify(data)
    }),
    
    // 字段管理
    fields: {
      // 添加字段
      add: (formId, data) => request(`/forms/${formId}/fields`, {
        method: 'POST',
        body: JSON.stringify(data)
      }),
      
      // 更新字段
      update: (formId, fieldId, data) => request(`/forms/${formId}/fields/${fieldId}`, {
        method: 'PUT',
        body: JSON.stringify(data)
      }),
      
      // 删除字段
      delete: (formId, fieldId) => request(`/forms/${formId}/fields/${fieldId}`, {
        method: 'DELETE'
      })
    }
  },

  // 字段类型相关
  fieldTypes: {
    // 获取字段类型列表
    list: (params = {}) => {
      const searchParams = new URLSearchParams(params)
      return request(`/field-types?${searchParams}`)
    },
    
    // 获取字段类型详情
    getByType: (type) => request(`/field-types/${type}`),
    
    // 验证字段值
    validate: (type, value) => request(`/field-types/${type}/validate`, {
      method: 'POST',
      body: JSON.stringify({ value })
    }),
    
    // 创建字段类型（管理员）
    create: (data) => request('/field-types', {
      method: 'POST',
      body: JSON.stringify(data)
    }),
    
    // 更新字段类型（管理员）
    update: (type, data) => request(`/field-types/${type}`, {
      method: 'PUT',
      body: JSON.stringify(data)
    })
  }
  ,
  // 版本管理
  versions: {
    list: (projectId) => request(`/projects/${projectId}/versions`),
    publish: (projectId, data) => request(`/projects/${projectId}/versions`, {
      method: 'POST',
      body: JSON.stringify(data)
    }),
    get: (projectId, versionId) => request(`/projects/${projectId}/versions/${versionId}`),
    compare: (projectId, data) => request(`/projects/${projectId}/versions/compare`, {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }
  ,
  // 用户管理（仅 admin）
  users: {
    list: (params = {}) => {
      const searchParams = new URLSearchParams(params)
      return request(`/users?${searchParams}`)
    },
    create: (data) => request('/users', {
      method: 'POST',
      body: JSON.stringify(data)
    }),
    update: (id, data) => request(`/users/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data)
    }),
    updateStatus: (id, isActive) => request(`/users/${id}/status`, {
      method: 'PUT',
      body: JSON.stringify({ isActive })
    }),
    resetPassword: (id, newPassword) => request(`/users/${id}/reset-password`, {
      method: 'PUT',
      body: JSON.stringify({ newPassword })
    }),
    delete: (id) => request(`/users/${id}`, { method: 'DELETE' })
  }
}

// 专门的文档生成API（保持原有接口）
export const generateDocx = async (projectData) => {
  try {
    // 取消全局 orientation 注入，遵循每个表单的 formConfig.pageOrientation
    const payload = { ...projectData }
    // 如果是正式环境需要补充base_url
    const response = await fetch(`${API_BASE_URL}/createDocx`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${getToken()}`
      },
      body: JSON.stringify(payload)
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${projectData.name || 'document'}.docx`
    document.body.appendChild(a)
    a.click()
    a.remove()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('生成 Word 文档失败:', error)
    throw error
  }
}

export default api